package com.platform.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ArrayUtils;
import sun.rmi.runtime.Log;

import java.lang.reflect.Field;
import java.util.*;

public class MapUtils {

    /**
     * 更具指定key 重构数据结构
     * @param list
     * @param timeSize
     * @return
     */
    public static <T extends Map> Map<String, List<T>> dataFormat(List<T> list, String keyName, Integer timeSize){
        if(timeSize == null){
            timeSize = 16;
        }
        Map<String,List<T>> data = new HashMap<>(timeSize);
        String key = null;
        for (T item : list){
            if(!data.containsKey(key = item.get(keyName).toString())){
                ArrayList<T> tempList = new ArrayList<>();
                tempList.add(item);
                data.put(key, tempList);
            }else{
                data.get(key).add(item);
            }
        }
        return data;
    }

    /**
     *  通过
     * @param list  一级列表
     * @param tempMap 分类好的全部数据
     * @param depth 至少1层，否则没必要调用此方法
     * @param subName 二级名称
     * @param name 一级名称
     * @return
     */
    public static List<Map<String,Object>> format(List<Map<String,Object>> list,Map<String, List<Map<String,Object>>> tempMap, int depth,String subName,String name){
        List<Map<String,Object>> temp = null;
        for(Map<String,Object> item : list){
            if((temp = tempMap.get(item.get(name).toString())) != null){
                item.put(subName,temp);
                if(depth > 1){
                    format(temp,tempMap,depth-1,subName,name);
                }
            }
        }
        return list;
    }

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}
